﻿using Elasticsearch.Net;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ESTools
{
    public class ElasticSearchHelper
    {
        private static IEnumerable<Node> Nodes;
        private static string[] _uris;

        private static ElasticClient _client;


        public ElasticSearchHelper() { }

        public static void Init(params string[] uris)
        {
            if (uris == null || uris.Any(s => string.IsNullOrEmpty(s)))
            {
                throw new ArgumentNullException("uris不能为null或者包含null");
            }
            _uris = uris;
            int count = uris.Length;
            List<Uri> uriList = new List<Uri>(count);
            for (int i = 0; i < count; i++)
            {
                Uri node = new Uri(uris[i]);
                uriList.Add(node);
            }
            StaticConnectionPool pool = new StaticConnectionPool(uriList);
            ConnectionSettings settings = new ConnectionSettings(pool);
            _client = new ElasticClient(settings);
        }

        static void Main()
        {
            ElasticSearchHelper.Init("http://192.168.52.128:9200");
            MyTestDoc Doc = new MyTestDoc
            {
                Title = "doc文字",
                Content = "瞎写",
                Author = "lut",
                PublishTime = DateTime.Now
            };
            
            var resp = _client.Index<MyTestDoc>(Doc, s => s.Index("title"));
            string id = resp.Id;
        }
    }

    [ElasticsearchType(Name = "ElasticsearchType", IdProperty = "Title")]
    public class MyTestDoc
    {
        [Number(NumberType.Long, Name = "Title")]
        public string Title { get; set; }

        [Keyword(Name = "Author", Index = true)]
        public string Author { get; set; }

        [Text(Name = "Content", Index = true)]
        public string Content { get; set; }

        [Date(Name = "PublishTime")]
        public DateTime PublishTime { get; set; }
    }
}